﻿/***********************/
/* (c) Alexandru Lungu */
/*  Challenge is Life! */
/* www.challenge-me.ws */
/***********************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Channels;

namespace Coowork.WcfCommon
{
    public class Credentials
    {
        public const string CredentialsHeader = "Credentials";
        public const string CredentialsNamespace = "http://www.challenge-me.ws";
        public const int ExpiresTimeSpan = 10000; //miliseconds

        public string UserName { get; set; }
        public string Password { get; set; }
        public DateTime Expires { get; set; }

        #region Static

        public static TimeSpan ClientServerTimeSpan { get; private set; }

        public static DateTime ServerDateTime
        {
            get
            {
                return DateTime.Now - ClientServerTimeSpan;
            }
            set
            {
                ClientServerTimeSpan = DateTime.Now - value;
            }
        }

        public MessageHeader ToMessageHeader()
        {
            this.Expires = DateTime.Now.AddMilliseconds(ClientServerTimeSpan.TotalMilliseconds + ExpiresTimeSpan);
            MessageHeader header = MessageHeader.CreateHeader(CredentialsHeader, CredentialsNamespace, this);
            return header;
        }

        public static Credentials FromMessageHeader(Message message)
        {
            int tokenPosition = message.Headers.FindHeader(CredentialsHeader, CredentialsNamespace);
            Credentials credentials = message.Headers.GetHeader<Credentials>(tokenPosition);
            return credentials;
        }

        #endregion

    }
}
